package com.zerui.manager.access.auth.task.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zerui.manager.access.auth.task.domain.AuthTaskDetail;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Getter
@Setter
@TableName("tb_access_auth_task_detail")
public class AccessAuthTaskDetailDO {

    /**
     * 主键
     */
    @TableId(type = IdType.AUTO)
    private Long id;
    /**
     * 权限组
     */
    private Long accessAuthId;
    /**
     * 任务ID
     */
    private Long taskId;
    /**
     * 设备ID
     */
    private Long deviceId;
    /**
     * 人员ID
     */
    private Long personnelId;
    /**
     * 操作（0 - 添加；1 - 删除）
     */
    private Integer operate;
    /**
     * 任务下发状态（0 - 未执行；1 - 执行中；2 - 执行失败）
     */
    private Integer syncStatus;
    /**
     * 创建时间
     */
    private LocalDateTime createTime;
    /**
     * 更新时间
     */
    private LocalDateTime updateTime;
    /**
     * 请求ID
     */
    private String requestId;
    /**
     * 返回结果
     */
    private String responseData;
    /**
     * 重试次数
     */
    private Integer retryTimes;

    public static List<AccessAuthTaskDetailDO> ofBatch(Long taskId, List<AuthTaskDetail> details) {
        if (CollectionUtils.isEmpty(details)) {
            return Collections.emptyList();
        }
        return details.stream().map(e -> AccessAuthTaskDetailDO.of(taskId, e)).collect(Collectors.toList());
    }

    public static AccessAuthTaskDetailDO of(Long taskId, AuthTaskDetail detail) {
        AccessAuthTaskDetailDO entity = new AccessAuthTaskDetailDO();
        entity.taskId = taskId;
        entity.deviceId = detail.getDeviceId();
        entity.accessAuthId = detail.getAccessAuthId();
        entity.personnelId = detail.getPersonnelId();
        entity.operate = detail.getOperate();
        entity.syncStatus = 0;
        entity.createTime = LocalDateTime.now();
        entity.updateTime = LocalDateTime.now();
        entity.retryTimes = 0;
        return entity;
    }

    public AuthTaskDetail toDomain() {
        AuthTaskDetail domain = new AuthTaskDetail();
        domain.setId(this.id);
        domain.setAccessAuthId(this.accessAuthId);
        domain.setTaskId(this.taskId);
        domain.setDeviceId(this.deviceId);
        domain.setPersonnelId(this.personnelId);
        domain.setOperate(this.operate);
        domain.setSyncStatus(this.syncStatus);
        domain.setRequestId(this.requestId);
        domain.setResponseData(this.responseData);
        domain.setRetryTimes(this.retryTimes);
        return domain;
    }
}
